import { INode } from './type';

export function getNodePaths(id: INode['id'], nodeList: INode[]) {
  const paths: INode[] = [];
  function eachNode(nodeList?: INode[]) {
    if (!nodeList?.length) return false;

    for (const node of nodeList) {
      paths.push(node);
      if (node.id === id) {
        return true;
      }
      if (eachNode(node.children)) return true;
      paths.pop();
    }

    return false;
  }

  eachNode(nodeList);
  return paths;
}

export function getNodeById(id: INode['id'], nodeList: INode[]) {
  const paths = getNodePaths(id, nodeList);
  const length = paths.length;
  if (!length) return null;
  const node = paths.pop() as INode;
  const parent = paths.pop();

  return {
    node,
    parent: parent || null,
    paths,
  };
}
